﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

public class Pagination
{
    /// <summary>
    /// 获取分页
    /// </summary>
    /// <param name="TableName">表名</param>
    /// <param name="ReturnFields">返回的列</param>
    /// <param name="Sort">排序字段</param>
    /// <param name="PK">主键</param>
    /// <param name="PageSize">页尺寸</param>
    /// <param name="p">页码</param>
    /// <param name="Where">查询条件</param>
    /// <returns>返回的DataTable</returns>
    public static DataTable GetPagination(string TableName, string ReturnFields, string Sort, string PK, int PageSize, int p, string Where)
    {
        if (p == 1)
        {
            return DBHelper.GetDataTable("select top " + PageSize + " " + ReturnFields + " from " + TableName + " " + (string.IsNullOrEmpty(Where) ? "" : " where " + Where) + " order by " + (string.IsNullOrEmpty(Sort) ? PK : Sort));
        }
        else
        {
            return DBHelper.GetDataTable("select " + ReturnFields + " from (select *,ROW_NUMBER() OVER (order by " + (string.IsNullOrEmpty(Sort) ? PK : Sort) + ") as RowNumber from " + TableName + " " + (string.IsNullOrEmpty(Where) ? "" : " where " + Where) + ") " + TableName + " where RowNumber > " + ((p - 1) * PageSize) + " and RowNumber <= " + (p * PageSize));
        }

    }
    /// <summary>
    /// 获取总条数
    /// </summary>
    /// <param name="TableName">表名</param>
    /// <param name="Where">查询条件</param>
    /// <returns></returns>
    public static int GetCount(string TableName, string Where = "")
    {
        return int.Parse(DBHelper.GetDataTable("select count(0) from " + TableName + " " + (string.IsNullOrEmpty(Where) ? "" : " where " + Where)).Rows[0][0].ToString());
    }
}
